package com.Jesse.MyBook;

import java.io.IOException;
import java.io.InputStream;
import java.lang.String;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

public class BookSearcher {
	public BookSearcher() {
		book = new BookInfo();
	}
	
	public BookInfo getResult(String isbn) 		
		throws ClientProtocolException, IOException, IllegalStateException,	XmlPullParserException {
		book = getResultByIsbn(isbn);
		return(book);
	}
	
	private BookInfo getResultByIsbn(String isbn)
		throws ClientProtocolException, IOException, IllegalStateException,	XmlPullParserException {
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(url_DB_api + isbn);
		HttpResponse response = client.execute(get);
		return getBookInfo(response.getEntity().getContent());
	}

	private BookInfo getBookInfo(InputStream inputStream)
		throws XmlPullParserException, IOException {
		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		factory.setNamespaceAware(true);
		XmlPullParser parser = factory.newPullParser();
		parser.setInput(inputStream, "UTF-8");
		BookInfo book = new BookInfo();

		for (int i = parser.getEventType(); i != XmlPullParser.END_DOCUMENT; i = parser.next()) {
			if (i == XmlPullParser.START_TAG && parser.getName().equals("attribute") && parser.getAttributeValue(0).equals("title")) {
				book.setTitle(parser.nextText());
				continue;
			}
			
			if (i == XmlPullParser.START_TAG && parser.getName().equals("attribute") && parser.getAttributeValue(0).equals("author")) {
				book.setAuthor(parser.nextText());
				continue;
			}
			
			if (i == XmlPullParser.START_TAG && parser.getName().equals("attribute") && parser.getAttributeValue(0).equals("price")) {
				book.setPrice(parser.nextText());
				continue;
			}
			
			if (i == XmlPullParser.START_TAG && parser.getName().equals("rating")) {
				book.setRating(parser.getAttributeValue(0));
				book.setRaters(parser.getAttributeValue(3));
				continue;
			}
		}
		return book;
	}
	
	private BookInfo book;
	private static String url_DB_api = "http://api.douban.com/book/subject/isbn/";

}
